﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using GeneralLibs;
using BasicForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GeneralLibs;
using CustomSecurity;
using Lists;
using ListForms;
using BasicForms;
using System.IO;
using System.Diagnostics;

namespace Portal.PhanHe
{
    public partial class UcDangNhap : UserControl
    {
        public delegate void OnAcceptLoginSuccessHandler (User user);
        public event OnAcceptLoginSuccessHandler AcceptLoginSuccess;

        private bool _ShowError = true;

        public UcDangNhap()
        {
            InitializeComponent();
        }

        //Property
        public string UserName
        {
            get
            {
                return txtUserName.Text;
            }
            set
            {
                txtUserName.Text = value;
            }
        }
        public string Password
        {
            get
            {
                return txtPassword.Text;
            }
            set
            {
                txtPassword.Text = value;
            }
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                switch (keyData)
                {
                    case Keys.F1:
                        GeneralLibs.CommonLib.ShowHelp(this.Name);
                        break;
                    case Keys.Control | Keys.L:
                    case Keys.Control | Keys.D:
                        Login();
                        break;
                    case Keys.Enter:
                        //if (tbxSQLServer.Focused || tbxDBUserName.Focused || tbxDBPassword.Focused || tbxDBName.Focused
                        //    || btnCheckConnectionInfo.Focused)
                        //    btnCheckConnectionInfo_Click(null, null);
                        //else
                            btnLoginLogout_Click(null, null);
                        break;

                    //Some hide functions
                    case Keys.Control | Keys.Shift | Keys.Alt | Keys.C:
                        FrmCauHinhCoSoDuLieu frmCauHinhCoSoDuLieu = new FrmCauHinhCoSoDuLieu();
                        frmCauHinhCoSoDuLieu.Show();
                        break;
                    case Keys.Control | Keys.Shift | Keys.Alt | Keys.A:
                        FrmEditThongSoAnChoDeveloper frm = new FrmEditThongSoAnChoDeveloper();
                        frm.Show();
                        break;
                }
                return base.ProcessCmdKey(ref msg, keyData);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                return false;
            }
        }

        //Phần Master
        private void UcDangNhap_Load(object sender, EventArgs e)
        {
            grpThongSo.Visible = false;

            if (LocalSettings.HeThong != null && LocalSettings.HeThong.RememberIDPass)
            {
                txtPassword.Text = LocalSettings.HeThong.Password;
                txtUserName.Text = LocalSettings.HeThong.TenTruyCap;
                chkRememberIDPass.Checked = true;
                chkAutoLogin.Checked = LocalSettings.HeThong.AutoLogin;
            }
            txtUserName.Focus();

            btnLoginLogout.Focus();
        }

        private void txtUserName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnLoginLogout_Click(sender, e);
                e.Handled = true;
            }
        }
        private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnLoginLogout_Click(sender, e);
                e.Handled = true;
            }
        }
        private void chkRememberIDPass_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkRememberIDPass.Checked) chkAutoLogin.Checked = false;
            chkAutoLogin.Enabled = chkRememberIDPass.Checked;
        }

        private void btnShowThietLap_Click(object sender, System.EventArgs e)
        {
            if (grpThongSo.Visible)
                grpThongSo.Visible = false;
            else
                grpThongSo.Visible = true;
        }

        private void btnLoginLogout_Click(object sender, System.EventArgs e)
        {
            Login();

            if (BasicForms.FrmProgressBarDev.ShowProgressBar) BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        //Phần thiết lập thông số
        private void grpThongSo_Paint(object sender, PaintEventArgs e)
        {
            SqlConnection con = new SqlConnection(LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("SELECT Name FROM master.dbo.sysdatabases ORDER BY Name");
                SqlDataAdapter _DataAdapter = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                dt.Clear();
                _DataAdapter.Fill(dt);

                cmbTenCSDL.DataSource = dt.DefaultView;
                cmbTenCSDL.ValueColumn = "Name";
                cmbTenCSDL.AddVisibleColumn("Name", "Tên CSDL");
                cmbTenCSDL.DisplayColumn = "Name";
            }
            catch (Exception ex)
            {
            }
            finally
            {
                FrmProgressBarDev.FinishShowProgress();
                if (con.State == ConnectionState.Open) con.Close();
            }

            if (LocalSettings.HeThong == null)
            {
                LocalSettings.HeThong = new LocalSettings();
            }
            else
            {
                if (tbxSQLServer.Text == "" && cmbTenCSDL.Text == "" && tbxDBUserName.Text == "")
                {
                    cmbTenCSDL.EditValue = LocalSettings.HeThong.DB_Name;
                    tbxDBPassword.Text = LocalSettings.HeThong.DB_PASS;
                    tbxDBUserName.Text = LocalSettings.HeThong.DB_UID;
                    tbxSQLServer.Text = LocalSettings.HeThong.DB_Server;
                    txtConnString.Text = LocalSettings.HeThong.DB_ConnectionString;
                }
            }
        }

        private void btnCheckConnectionInfo_Click(object sender, System.EventArgs e)
        {
            if (CauHinhOK())
            {
                if (MessageBox.Show("Kết nối thành công đến cơ sở dữ liệu.\nPhần mềm cần khởi động lại để kết nối với thông số vừa thay đổi\n.Bạn có muốn khởi động lại không?", "Cảnh báo",
                     MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    Application.Restart();
                    grpThongSo.Visible = false;
                }

                LocalSettings.HeThong.DB_Name = cmbTenCSDL.Text.Trim();
                LocalSettings.HeThong.DB_PASS = tbxDBPassword.Text;
                LocalSettings.HeThong.DB_UID = tbxDBUserName.Text.Trim();
                LocalSettings.HeThong.DB_Server = tbxSQLServer.Text.Trim();
                LocalSettings.HeThong.DB_ConnectionString = txtConnString.Text;
                LocalSettings.HeThong.Save2File();
            }
            else
                MessageBox.Show("Không thể tạo kết nối tới cơ sở dữ liệu. Bạn hãy xem lại những thông tin hệ thống.");
        }

        private bool CauHinhOK()
        {
            FrmProgressBarDev.StartShowProgress();
            using (SqlConnection con = new SqlConnection())
            {
                if (cmbTenCSDL.Text != "")
                    con.ConnectionString = "Data Source=" + tbxSQLServer.Text.Trim() +
                                           ";initial catalog=" + cmbTenCSDL.Text.Trim() +
                                           ";User ID=" + tbxDBUserName.Text.Trim() +
                                           ";PWD=" + tbxDBPassword.Text;
                else
                    con.ConnectionString = "Data Source=" + tbxSQLServer.Text.Trim() +
                                         ";User ID=" + tbxDBUserName.Text.Trim() +
                                         ";PWD=" + tbxDBPassword.Text;
                try
                {
                    con.Open();

                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT Name FROM master.dbo.sysdatabases ORDER BY Name");
                    SqlDataAdapter _DataAdapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    dt.Clear();
                    _DataAdapter.Fill(dt);

                    cmbTenCSDL.DataSource = dt.DefaultView;
                    cmbTenCSDL.ValueColumn = "Name";
                    cmbTenCSDL.AddVisibleColumn("Name", "Tên CSDL");
                    cmbTenCSDL.DisplayColumn = "Name";
                }
                catch (Exception ex)
                {
                    FrmProgressBarDev.FinishShowProgress();
                    return false;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
            FrmProgressBarDev.FinishShowProgress();
            return true;
        }

        //Setting
        private bool CheckLicence()
        {
            try
            {
                while (true)
                {
                    string inputSerial = LocalSettings.HeThong.SerialKey;

                    string actualCpuSerial = CommonLib.MaHoaMD5("Accounting" + CommonLib.MaHoaMD5("Accounting" + CommonLib.GetMacAddressID())) + "C";
                    if (inputSerial == actualCpuSerial)
                    {
                        return true;
                    }

                    string actualCompanyNameSerial = CommonLib.MaHoaMD5("Accounting" + Config.TenDoanhNghiep) + "B";
                    if (inputSerial == actualCompanyNameSerial)
                    {
                        if (CommonLib.GetSystemDateTime() > LocalSettings.HeThong.HanSuDung)
                        {
                            MessageBox.Show("Sản phẩm đã hết hạn sử dụng");
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }

                    FrmSerial frmSerial = new FrmSerial();
                    if (frmSerial.ShowDialog() != DialogResult.OK)
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                return false;
            }
        }
        public void Login()
        {
            try
            {
                if (User.CurUser == null)//login
                {
                    if (txtUserName.Text == "")
                    {
                        MessageBox.Show("Tên truy cập không được để trống");
                        txtUserName.Focus();
                        return;
                    }

                    #region Save to LocalSettings
                    try
                    {
                        if (chkRememberIDPass.Checked)
                        {
                            LocalSettings.HeThong.TenTruyCap = txtUserName.Text.Trim();
                            LocalSettings.HeThong.Password = txtPassword.Text;
                            LocalSettings.HeThong.TenTruyCapHienTai = txtUserName.Text.Trim();
                            LocalSettings.HeThong.PasswordHienTai = txtPassword.Text;
                            LocalSettings.HeThong.RememberIDPass = true;
                            LocalSettings.HeThong.AutoLogin = chkAutoLogin.Checked;
                            LocalSettings.HeThong.Save2File();
                        }
                        else
                        {
                            LocalSettings.HeThong.TenTruyCap = "";
                            LocalSettings.HeThong.Password = "";
                            LocalSettings.HeThong.TenTruyCapHienTai = txtUserName.Text.Trim();
                            LocalSettings.HeThong.PasswordHienTai = txtPassword.Text;
                            LocalSettings.HeThong.RememberIDPass = false;
                            LocalSettings.HeThong.AutoLogin = false;
                            LocalSettings.HeThong.Save2File();
                        }
                    }
                    catch (Exception ex)
                    {
                        BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                    }
                    #endregion

                    try
                    {
                        SqlConnection con = new SqlConnection(LocalSettings.ConnectString);
                        try
                        {
                            if (con.State == System.Data.ConnectionState.Open)
                                con.Close();
                            con.Open();
                            Lists.Store store = Lists.DanhMucStore.Instance.GetByStoreID(Config.StoreID);
                            //if (store != null) lblVersion.Text = string.Format("Phiên bản: {0} - {1}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version, store.Ten);
                            //else lblVersion.Text = string.Format("Phiên bản: {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);

                            //if (!CheckLicence()) return;

                            try
                            {
                                User.CurUser = User.Login(UserName, Password);
                                if (User.CurUser != null)
                                {
                                    //NhatKySuDung.Insert2DB("Đăng nhập", "hệ thống");
                                    if (AcceptLoginSuccess != null) AcceptLoginSuccess(User.CurUser); //Thành công thì báo cho Form KinhDoanh
                                }
                            }
                            catch (Exception ex)
                            {
                                if (_ShowError)
                                    MessageBox.Show(ex.Message, "Lỗi đăng nhập");
                                _ShowError = !_ShowError;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Không thể kết nối đến cơ sở dữ liệu", "Lỗi đăng nhập");
                        }

                        
                    }
                    catch (Exception loginEx)
                    {
                        MessageBox.Show(loginEx.Message, "Lỗi đăng nhập");
                    }
                }
                if(this.Visible)
                    SetGUI();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void SetGUI()
        {
            if (User.CurUser != null)
            {
                btnLoginLogout.Text = "Đăng xuất";
            }
            else
            {
                btnLoginLogout.Text = "Đăng nhập";
            }
        }

        private void cmbTenCSDL_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = "Data Source=" + tbxSQLServer.Text.Trim() +
                                     ";User ID=" + tbxDBUserName.Text.Trim() +
                                     ";PWD=" + tbxDBPassword.Text;
                try
                {
                    con.Open();

                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT Name FROM master.dbo.sysdatabases ORDER BY Name");
                    SqlDataAdapter _DataAdapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    dt.Clear();
                    _DataAdapter.Fill(dt);

                    cmbTenCSDL.DataSource = dt.DefaultView;
                    cmbTenCSDL.ValueColumn = "Name";
                    cmbTenCSDL.AddVisibleColumn("Name", "Tên CSDL");
                    cmbTenCSDL.DisplayColumn = "Name";
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }
    }
}
